package com.clr.springboot.contorller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.alibaba.druid.util.StringUtils;
import com.clr.springboot.entity.User;
import com.clr.springboot.service.UserService;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
import java.util.Map;
;
/**
 * @author 车礼荣
 * @version 1.0
 * Create by 2025/3/20 10:13
 */
@Controller
public class WebController {
    @Autowired
    private UserService userService;

    //登录界面
    @GetMapping("/tologin")
    public String tologin() {
        return "index";
    }

    //登录界面
    @PostMapping("/dologin")
    public String Login(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "password") String password,
            Map<String, Object> maps, HttpSession session,
    String code) {

//         1. 校验验证码
        String sessionCode = (String) session.getAttribute("code");
        if (StringUtils.isEmpty(code) || !code.equalsIgnoreCase(sessionCode)) {
            return "验证码错误";
        }

        // 2. 校验用户名密码
        User user = userService.login(name, password);
        if (user != null) {
            session.setAttribute("user", user);
            return "redirect:/main";
        }else {
            maps.put("msg", "用户密码或名字不正确");
            return "login";
        }
    }
//    登陆验证
    @GetMapping("/captcha")
    public void generateCaptcha(HttpSession session,HttpServletResponse response) throws IOException {
        // 生成线条干扰验证码（宽200px，高100px，4位字符，10条干扰线）
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 10);
        String code = lineCaptcha.getCode(); // 获取验证码文本
        session.setAttribute("code",code);
        lineCaptcha.write(response.getOutputStream()); // 输出到响应流
        response.getOutputStream().close(); // 关闭流防止资源泄漏
}


//
//    //用户列表界面
//    @GetMapping("/getUserlist")
//    public String getList(Model model) {
//        List<User> userList = userService.getUserList();
//        if (userList != null) {
//            model.addAttribute("userList", userList);
//            return "ulist";
//        } else {
//            return null;
//        }
//    }
//
//    //退出功能
    @PostMapping("/quit")
    public String quit(HttpSession session, HttpServletResponse response) {
        session.invalidate(); // 销毁会话
        return "redirect:/Login";
    }

    //查询单个用户
    @GetMapping("/FindUser/{id}")
    public String FindByid(@PathVariable("id") Integer id, Model model) {
        User user = userService.FindByid(id);
        model.addAttribute("user", user);
        if (user != null)
            return "detail";
        else
            return null;
    }

    //按照id删除用户
    @RequestMapping("/delUser/{id}")
    public String delUser(@PathVariable("id") Integer id, Model model) {
        int rows = userService.delUser(id);
        if (rows > 0) {
            model.addAttribute("msg", "delete success!");
            return "forward:/getUserList";
        } else {
            model.addAttribute("msg", "delete fail!");
            return "forward:/getUserList";
        }
    }

    //更新用户
    @GetMapping("/toUpdate/{id}")
    public String TOupUser(@PathVariable("id") Integer id, Model model) {
        User user = userService.selectByid(id);
        model.addAttribute("user", user);
        return "update";
    }

    //修改用户
    @RequestMapping("/UpdateUser")
    public String updateUser(User user, Model model, RedirectAttributes redirectAttributes, HttpSession session) {
        int rows = userService.updateUser(user);
        if (rows > 0) {
//        model.addAttribute("msg","updata success!!");
            redirectAttributes.addFlashAttribute("msg", "update success!!");
//        session.setAttribute("msg","updata success!!");
        } else {
//            model.addAttribute("msg","updata fail!!");
//            session.setAttribute("msg","updata fail!!");
            redirectAttributes.addFlashAttribute("msg", "update success!!");
        }
        return "redirect:/getUserList";
    }

    //添加用户
    @RequestMapping("/AddUser")
    public String addUser(User user, RedirectAttributes redirectAttributes, HttpSession session) {
        int rows = userService.addUser(user);
        if (rows > 0) {
            redirectAttributes.addFlashAttribute("msg", "insert success!!");

        } else {
            redirectAttributes.addFlashAttribute("msg", "insert success!!");
            return "redirect:/getUserList";
        }
        return "redirect:/getUserList";
    }


//    @GetMapping("/search")
//    public String searchUsers(
//            @RequestParam(value = "name", required = false) String name,
//            @RequestParam(value = "age", required = false) Integer age,
//            Model model
//    ) {
//        List<User> users = userService.searchUsers(name, age);
//        model.addAttribute("users", users);
//        model.addAttribute("name", name);
//        model.addAttribute("age", age);
//        return "ulist";
//    }
//改造原来的查询方法
@GetMapping("/getUserList")
public String list(
        @RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "age", required = false) Integer age,
        @RequestParam(defaultValue = "1") Integer pageNum,
        @RequestParam(defaultValue = "5") Integer pageSize,
        Model model) {
    // 调用分页查询
    PageInfo<User> pageInfo = userService.findByCondition(name, age, pageNum, pageSize);
    // 将结果传递给前端
    model.addAttribute("pageInfo", pageInfo);
    model.addAttribute("name",name);
    model.addAttribute("age",age);

    return "ulist";
}


//注册
    @PostMapping("/register")
    public String FindByUsername(User user, Model model) {
        if (userService.FindByUsername(user.getName()) != null) {
            model.addAttribute("msg", "用户已经被注册");
            return "/register";
        }
        userService.addUser(user);
        return "/login";
    }

    // 批量删除
    @PostMapping("/batchDelete")
public String batchDelete(@RequestParam("ids") List<Integer> ids) {
    userService.batchDelete(ids);
    return "redirect:/getUserList"; // 删除后重定向到列表页
}}
//




